<?php
/**
 * Create By: PhpStorm
 * User: yihua
 * File: UserFavorite.php
 * Date: 2017/1/10
 * Time: 0:45
 */
namespace app\api\model\dao;

use think\Db;
use think\Model;
use app\library\Flag;

class UserFavorite extends Model
{
    protected $table = 'user_favorite';

    /**
     * @param $user_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getFavorite($user_id, $fav_type)
    {
        $conds = array(
            'user_id' => ['=', $user_id],
            'status' => ['=', Flag::USER_FAVORITE_ACTIVE],
            'fav_type' => ['=', $fav_type],
        );
        return $this->where($conds)->select();//返回包含object的数组
    }

    public function addFavite($param)
    {
        $data = [
            'user_id' => $param['user_id'],
            'fav_type' => $param['fav_type'],
            'fav_id' => $param['fav_id'],
            'title' => $param['title'],
            'description' => $param['description'],
            'fav_time' => time(),
            'status' => Flag::USER_FAVORITE_ACTIVE,
        ];
        return $this->save($data);

    }

    public function removeFavorite($user_id, $id, $type)
    {
        $conds = array(
            'fav_id' => $id,
            'fav_type' => $type,
            'user_id' => $user_id,
        );
        $field = array(
            'status' => Flag::USER_FAVORITE_DELETED,
        );
        return $this->where($conds)->update($field);

    }

    public function getFavoriteCountByType($fav_type, $fav_id = 0, $userid = 0)
    {
        $conds = array(
            'fav_type' => $fav_type,
            'status' => Flag::USER_FAVORITE_ACTIVE,
        );
        if (!empty($fav_id)) {
            $conds['fav_id'] = $fav_id;
        }
        if (!empty($userid)) {
            $conds['user_id'] = $userid;
        }
        return Db::table($this->table)->where($conds)->group('user_id')->count();

    }

}